// 组装带有二级表头的表格
/**
 * 
 * @param titleData 表头数据
 * @param valueData 返回数据
 */
export function assTable(titleData:any,valueData:any,tableName:string){
    let headerFirst = ''; //一级表头
    let headerSecond = '';//二级表头
    let tableVals:any[]  = [];
    let checkHeaderName:any[] = [];
    let cloneData = JSON.parse(JSON.stringify(valueData)); //深度克隆valueData
    let body = "";
    titleData.forEach((o:any) => {
        headerFirst += `<th colspan="${o.children?.length > 0 ? o.children.length : 1}" rowspan="${o.children?.length > 0 ? 1 : 2}">${o.headerName}</th>`;
        
        if(o.field){
            checkHeaderName.push(o.field);
        }
        if (o.children?.length > 0) {
            o.children.forEach((v:any) => {
                headerSecond += `<th>${v.headerName}</th>`
                if(v.field){
                    checkHeaderName.push(v.field);
                }
            });
        }
    });
    // console.log(checkHeaderName,cloneData);
    cloneData.forEach((item:any) => { 
        for (let key in item) { 
            if(key === 'auditState'){
                item[key] = item[key] > 0 ? '已审核' :'未审核'
            };
            if(checkHeaderName.indexOf(key) !== -1){ 
                item[key] = `<td>${item[key] || ''}</td>`
            }else{
                console.log(key);
            }
            
        };
        tableVals.push([...Object.values(item)]);
    });
    tableVals.forEach(o => {
        let strs = '<tr>'
        o.forEach((v:any) => {
            strs += v
        });
        strs += '</tr>';
        body += strs;
    });
    let tableHead = `<thead> 
         <tr>${headerFirst}</tr> 
         <tr>${headerSecond}</tr>
   </thead>`
    tableToXlsx( tableHead,tableName, body);
};

function tableToXlsx(head: any, filename: any, body: any) {
    const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
    <head><meta charset="UTF-8"></head>
    <body><table border="1">${head}${body}</table></body>
</html>`;

  try {
    const a = document.createElement('a');
    a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
    a.download = filename;
    a.click();
    document.removeChild(a);
  } catch (err) {
    console.log(err);
  }
}